const express = require('express')
const cors = require('cors')
const path = require('path')
const fs = require('fs')
let wsObj = null
let allData = {}  // 所有表格数据,专门用来给前端展示用的
// const mySQL = require('./mySQL')
const staticPath = path.join(__dirname, '..', 'static')
const sourceMapDir = path.join(staticPath,'sourceMap')
const multiparty = require("multiparty")

const router = express.Router()

router.ws('/socket', (ws, req) => {
  wsObj = ws
  console.log('socket启动')
  // ws.on("message", function (msg) {
  //   ws.send("我收到你的消息-" + msg)
  // })
  wsObj.send(JSON.stringify({ result: 1, data: allData }))  // webSocket只能发送字符串给前端,所以要使用JSON.stringify转成JSON字符串
})
// 接收客户端传过来的数据
router.post('/sendData', cors(), (req, res) => {
  const multipart = new multiparty.Form()
  multipart.parse(req, async (err, fields, files) => {
    if (!err) {
        const data = {}
        for (const key in fields) { data[key] = fields[key][0] }
        const type = data.type
        if(type === 'error' && files.events){
          const buffer = fs.readFileSync(files.events[0].path)
          const endPath = path.join(staticPath,'cache',`${data.lineNumber}_${data.columnNumber}_${data.currentTime}.zip`)
          fs.writeFileSync(endPath,buffer)
          data.isHaveEvents = true
        }
        if (!allData[type]) { allData[type] = [] }
        // 如果是error类型,进行错误去重
        if(type === 'error'){
          const needPrototypeArr = ['errorType','message','fileName','columnNumber','lineNumber']
          const oldData = JSON.parse(JSON.stringify(data))
          const allErrors = JSON.parse(JSON.stringify(allData[type]))
          for (let i = 0; i < allErrors.length; i++) {
            const item = allErrors[i]
            for (const key in item) {
              !needPrototypeArr.includes(key) ? delete item[key] : ''
            }
            allErrors[i] = JSON.stringify(item)
          }
          for (const key in oldData) {
            !needPrototypeArr.includes(key) ? delete oldData[key] : ''
          }
          const errorStr = JSON.stringify(oldData)
          // console.log(allErrors)
          // console.log(errorStr)
          if (~allErrors.indexOf(errorStr)) {
            res.send({ result: -1, msg: '该报错已经有了' })
            return
          }else{
            console.log('没有这个报错,可以追加')
          }
        }
        allData[type].unshift(data)
        if (wsObj) {
          wsObj.send(JSON.stringify({ result: 1, data: allData }))
          res.send({ result: 1, mes: '接收成功' })
        }else{
          res.send({ result: 1, msg: '接收成功,web端没有连接服务器的weSocket'})
        }
    } else {
      res.send({ result: -1, msg: '接收失败', data: err })
    }
  })
})
// 获取视频文件
router.post('/getRadio', cors(), (req, res) => {
  const {columnNumber,lineNumber,currentTime} = req.body
  const endPath = path.join(staticPath,'cache',`${lineNumber}_${columnNumber}_${currentTime}.zip`)
  const buffer = fs.readFileSync(endPath)
  res.send(buffer)
})
// 存储sourceMap文件
router.post('/setSourceMap', cors(), (req, res) => {
  const {pathArr,name} = req.body.data
  let finishNumber = 0
  // 先清空再创建
  const endPath = path.join(sourceMapDir,name)
  if(!fs.existsSync(endPath)){ fs.mkdirSync(endPath) }  // 查看有没这个文件夹.没有就创建这个文件夹
  const sourceMapFiles = fs.readdirSync(endPath)
  for (const item of sourceMapFiles) {
    item !== '.gitignore' ? fs.unlinkSync(path.join(endPath,item)) : ''
  }
  for (const item of pathArr) {
    const buffer = fs.readFileSync(item.path)  // 根据file对象的路径获取file对象里的内容
    fs.writeFile(path.join(endPath,item.name),buffer,(err)=>{
        if(!err){
          finishNumber++
          if(pathArr.length === finishNumber){
            res.send({ result: 1, message:'上传完成'})
          }
        }
    })
  }
})
// 根据文件名获取指定的sourceMap
router.post('/getSourceMap', cors(), (req, res) => {
  const { fileName,entryName } = req.body
  try {
    const needFileName = fileName.split('/').slice(-1)[0] + '.map'
    const sourceMapPath = path.join(sourceMapDir,entryName,needFileName)
    console.log(sourceMapPath,'sourceMapPath')
    const buffer = fs.readFileSync(sourceMapPath)
    res.send(buffer)
  } catch (error) {
    res.send({ result: -1, message:error})
    console.log('没有这个sourceMap文件')
  }
})
// 清空所有数据
router.post('/clear', cors(), (req, res) => {
  allData = []
  res.send({ result: 1, msg: '清空完成' })
})

router.get('/', cors(), (req, res) => {
  res.send('欢迎来到数据埋点')
})
router.get('/test1', cors(), (req, res) => {
  res.send({ result: 1, mes: '接收成功' })
})
router.get('/test2', cors(), (req, res) => {
  res.send({ result: 1, mes: '接收成功' })
})

module.exports = router